package com.report.controller;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.report.bean.Student;
import com.report.service.ClassService;
import com.report.service.SchoolService;
import com.report.service.StudentService;

@Controller
public class StudentController {
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private SchoolService schoolService;
	
	@Autowired
	private ClassService classService;
	
	@Autowired
	private ConversionService conversionService;
	
	@RequestMapping(value="/index")
	public String listStudent(Map<String, Object> map){
		map.put("student", new Student(true));
		map.put("studentList", studentService.listStudent());
		map.put("schools", schoolService.listSchool());
		map.put("clazzes", classService.listClazz());
		return "student";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.POST, headers={"content-type=application/json"})
	@ResponseBody
	public String addStudent(@RequestBody Student st){
		if(st != null){
			studentService.addStudent(st);
			return String.valueOf(st.getId());
		}
		return "0";
	}
	
	@RequestMapping("/delete/{studentId}")
	public String removeStudent(@PathVariable("studentId") Integer studentId){
		studentService.removeStudent(studentId);
		return "redirect:/index";
	}
	
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		binder.setConversionService(this.conversionService);
	}
}
